package com.smartao.core;

import java.security.SecureRandom;
import java.util.zip.CRC32;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 以服务器信息生成ServerID
 * @author Ricky
 */
public class SIDManager {

	private static final String CHARACTER_POOL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
	private static final Logger logger = LoggerFactory.getLogger(SIDManager.class);

	/**
	 * 根据指定的信息作为Seed生成服务器ID
	 * @param info info为null时生成默认SID
	 * @return
	 */
	public static String generateSID(String info) {
		try {
			byte[] seed = info == null ? "SMARTAO".getBytes() : info.getBytes();
			SecureRandom secrand = SecureRandom.getInstance("SHA1PRNG", "SUN");
			secrand.setSeed(seed);
			StringBuffer res = new StringBuffer();
			int charCount = 0;
			for (int i = 1; i < 24; i++)
				if (charCount == 5) {
					res.append('-');
					charCount = 0;
				} else {
					res.append(CHARACTER_POOL.charAt(secrand.nextInt(CHARACTER_POOL.length())));
					charCount++;
				}
			res.append(getCharacterForCRC(res.toString().getBytes()));
			return res.toString();
		} catch (Exception e) {
			logger.error("无法获取服务器ID", e);
			return null;
		}
	}

	private static char getCharacterForCRC(byte bytes[]) {
		CRC32 crc32 = new CRC32();
		crc32.update(bytes);
		long crcValue = crc32.getValue();
		int index = (int) (crcValue % CHARACTER_POOL.length());
		return CHARACTER_POOL.charAt(index);
	}
}
